const Model = require('../model/dbModel/index')
const {User,QuestionBase,Question,Op} = Model
const {getQuestionArray,getNotQuestionArray} = require('../model/appModel/json_schema/vaildata/questionVaildata')

//用户新建一个题库
async function createQuestionBase(qbinfo,user){
    let userinstance = undefined;
    console.log(qbinfo, user)
    if (user.username) {
        userinstance = await User.findOne({
            where: {
                username: user.username
            },
            row: true
        });
        console.log(userinstance);
        if(!userinstance) return {
            status:11,
            err:"该用户不存在"
        }
        else if(userinstance.userrole!='teacher') return{
            status:12,
            err:"该用户不是教师，暂时无法创建题库"
        }
    }
    let qb = {};
    qb.qb_name = qbinfo?.qb_name;    //获取题库的名字
    qb.qb_description = qbinfo.qb_description;//获取题库的介绍
    qb.qb_creator_id = userinstance.id;//获取题库的创建人id

    await userinstance.createQuestionBase(qb);
    return {
        status:0,
        msg:"创建成功"
    }
    //return await QuestionBase.create(qb);
}

//查看题库列表
async function QuestionBaseList(page,pageSize){

    if(!page || page<1 || !pageSize || pageSize<1) return{
        status:2,
        msg:"请输入正确的页码和页面大小"
    }
    let offset = (page-1)*pageSize;
    let result = await QuestionBase.findAll({
        offset:offset,
        limit:pageSize*1,//隐式转换
        //raw: true,
        logging:true,
        include:{
            model:User,
            attributes:[
                'username',
                'usernickname'
            ]
        },
        attributes:[
            ['id','qb_id'],
            'qb_name',
            'qb_description'
            //['username','用户名'],1
            //['usernickname','用户昵称']
        ]
    }).catch(function(e){
        //console.error(e)
        return {
            status:50,
            msg:"数据库出现了未知错误"
        }
    })
    //console.log(result)
    if(result?.status) return result;
    else return {
        data:result,
        status:0,
        msg:"查询成功"
    };
}

//查看题库列表
async function myQuestionBaseList(page,pageSize,username){

    if(!page || page<1 || !pageSize || pageSize<1) return{
        status:2,
        msg:"请输入正确的页码和页面大小"
    }
    let offset = (page-1)*pageSize;
    //查找用户
    let user = await User.findOne({
        where:{
            username:username
        }
    })
    //判断用户是否存在
    if(!user) return {
        status:11,
        msg:"用户不存在"
    }
    let result = await QuestionBase.findAll({
        offset:offset,
        limit:pageSize*1,//隐式转换
        //raw: true,
        //logging:true,
        where:{
            creatorid:user.id,
        },
        include:{
            model:User,
            attributes:[
                'username',
                'usernickname'
            ]
        },
        attributes:[
            ['id','qb_id'],
            'qb_name',
            'qb_description'
            //['username','用户名'],1
            //['usernickname','用户昵称']
        ]
    }).catch(function(e){
        //console.error(e)
        return {
            status:50,
            msg:"数据库出现了未知错误"
        }
    })
    //console.log(result)
    if(result?.status) return result;
    else return {
        data:result,
        status:0,
        msg:"查询成功"
    };
}

/*
* 用户删除自己的题库
* */
async function deleteQuestionBase(username,qb_ids){
    //查找用户
    let user = await User.findOne({
        where:{
            username:username
        }
    })
    //判断用户是否存在
    if(!user) return {
        status:11,
        msg:"用户不存在"
    }
    //判断用户是否有拥有删除的权限
    let qb = await user.getQuestionBases({
        where:{
            id:{
                [Op.in]:qb_ids
            },
            creatorid:user.id
        }
    })
    //console.log(qb)
    if(qb.length===0) return{
        status:12,
        msg:"用户"+username+"没有权限删除这些题库"
    }

    console.log(qb)

    //删除并且获取成功删除的条数
    let delnum =await QuestionBase.destroy({
        where:{
            id:{
                [Op.in]:qb_ids
            },
            creatorid:user.id
        }
    })
    return{
        status:0,
        successDeleteNum:delnum,
        msg:"删除成功"
    }


}
/*
* 用户更新题库基本信息
* */
async function updataQuestionBase(newqb,user){


}


//用户向自己的题库添加题目
async function addQuestions(username,QBid,arr){

    let questionArray = arr
    if(!Array.isArray(questionArray) ||
        !typeof QBid ==='number' ||!typeof username === 'string') return{
        status:21,
        msg:'请求参数类型异常'
    }
    //判断用户是否存在
    let user = await User.findOne({
        where:{
            username:username
        }
    })
    if(!user)return{
        status:11,
        msg:"该用户不存在"
    }
    //判断用户是否拥有题库
    let qb = await user.getQuestionBases({
        where:{
            id:QBid
        }
    }).catch(e =>console.log(e));
    if(qb.length === 0) return{
        status:12,
        msg:"该用户"+username+"无权限添加题目"
    }
    console.log("arr",arr)
    console.log("qb",qb)
    const qts = getQuestionArray(arr);
    console.log("qts",qts);
    //设置题目所属的题库和创建者
    for (let i = 0; i < qts.length; i++) {
        qts[i].creatorid = user.id;
        qts[i].QBID = QBid;
        if(!(qts[i]?.difficulty)) qts[i].difficulty = 0;
    }
    let insertresult =  await Question.bulkCreate(qts,{
        //validate:true
    })
    console.log("insertresult",insertresult)
    return {
        successDataNum:insertresult?.length??0,
        status:0,
        msg:"添加题目成功",
    }


}

async function deleteQuestions(){}

async function updataQuestions(){}

async function questionList(username,qbid,page,pageSize){
    //查找用户是否存在
    let user = await User.findOne({
        where:{
            username:username
        }
    })
    if(!user) return {
        status:11,
        msg:"用户不存在"
    }

    //查找题库是否存在
    let qb =await QuestionBase.findOne({
        where:{
            id:qbid
        },
        include:{
            model:User,
            where:{
                id:user.id
            },
            attributes:[
                ['username','用户名'],
                ['usernickname','用户昵称']
            ]
        }
    })

    if(!qb) return{
        status:12,
        msg:"用户权限不足"
    }

    if(!page || page<1 || !pageSize || pageSize<1) return{
        status:20,
        msg:"请输入正确的页码和页面大小"
    }
    let offset = (page-1)*pageSize;
    let result = await Question.findAll({
        offset:offset,
        limit:pageSize*1,//隐式转换
        //raw: true,
        logging:true,
        where:{
            QBID:qb.id
        },
        attributes:['id','title','qt_body','type','difficulty','analysis']

    }).catch(function(e){
        console.error(e)
        return {
            status:50,
            msg:"服务器出现了未知错误"
        }
    })
    //console.log(result)
    if(result?.status) return result;
    else return {
        data:result,
        status:0,
        msg:"查询成功"
    };
    return {
        name:"21312"
    };
}

async function test(){
    await addQuestions("D31",12,[{
        "title": "123",
        "type": 2,
        "analysis": "12312",
        "difficulty": 4,
        "qt_body": {
            "selections": [
                "12312",
                "3123",
                "12312",
                "312"
            ],
            "answers": [
                1,
                2,
                3,
                4
            ],
            "scoreDefault": [
                6.5
            ]
        }
    }])
}

test();


module.exports ={
    createQuestionBase,
    QuestionBaseList,
    myQuestionBaseList,
    deleteQuestionBase,
    updataQuestionBase,
    addQuestions,
    deleteQuestions,
    updataQuestions,
    questionList
}